import { Injectable } from '@nestjs/common';
import { CreateMailUserDto } from './dto/create-mail-user.dto';
import { UpdateMailUserDto } from './dto/update-mail-user.dto';
import { createTransport, Transporter } from 'nodemailer';
import { ConfigService } from '@nestjs/config';
import { EntityManager } from 'typeorm';
import { InjectEntityManager } from '@nestjs/typeorm';
import { MailUser } from './entities/mail-user.entity';

@Injectable()
export class MailUserService {
  transporter: Transporter;
  constructor(private configService: ConfigService) {
    this.transporter = createTransport({
      host: 'smtp.qq.com',
      port: 587,
      secure: false,
      auth: {
        user: this.configService.get('email_user'),
        pass: this.configService.get('email_password'),
      },
    });
  }

  @InjectEntityManager()
  private entityManager: EntityManager

  async findUserByEmail(email: string) {
    return await this.entityManager.findOneBy(MailUser, {
      email
    })
  }

  async sendEmail({ to, subject, html }) {
    console.log(this.configService.get('email_user'))
    await this.transporter.sendMail({
      from: {
        name: '系统邮件',
        address: this.configService.get('email_user')
      },
      to,
      subject,
      html,
    });
  }
  create(createMailUserDto: CreateMailUserDto) {
    return 'This action adds a new mailUser';
  }

  findAll() {
    return `This action returns all mailUser`;
  }

  findOne(id: number) {
    return `This action returns a #${id} mailUser`;
  }

  update(id: number, updateMailUserDto: UpdateMailUserDto) {
    return `This action updates a #${id} mailUser`;
  }

  remove(id: number) {
    return `This action removes a #${id} mailUser`;
  }
}
